<?php
/**
 *
 * @license http://www.gnu.org/licenses/gpl-3.0.txt
 * @encoding UTF-8
 *
 * All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
class Mur implements Page{
    public function main($args=NULL) {
        if (isset($args[0]) && $args[0]=='delete') $this->delete ();
        else if (isset($args[0]) && $args[0]=='publish') $this->publish ();
        else if (isset($args[0]) && !empty ($args[0])) $this->show ($args[0]);
        else $this->me ();
    }

    private function me() {
        if (!Session::getInstance()->sessionCheck()) header('Location: /index.php/');

        $friends = Storage::getInstance()->fetch()->query("SELECT ProfilTwo as p FROM Friends WHERE ProfilOne=".$_SESSION["id"]." UNION SELECT ProfilOne as p FROM Friends WHERE ProfilTwo=".$_SESSION["id"])->fetchAll(PDO::FETCH_ASSOC);

        $fs = array();
        $friendsData = array();
        foreach($friends as $f=>$v) {
            array_push($fs, $v['p']);
            $info = Database::select("Compte", "id, pseudo, avatar", "id=".$v['p']);
            $friendsData[$info[0]['id']] = $info[0];
        }

        foreach ($friendsData as $key => $value) {
            $str .= $value['pseudo'] . " ";
        }


        $where = implode(" OR Profil=", $fs);
        $tweets = Database::select("Tweet", "*", "Profil=".$_SESSION["id"]. " ".(empty($fs) ? "" : " OR Profil=".$where), NULL, "date");
       
        foreach($tweets as $t=>$v) {
                $v['content'] = preg_replace("/\@([a-zA-Z0-9.]{,11})/", "\@<a href='/index.php/Mur/$1'>$1</a>", $v['content']);

        }



        $S = Template::getSmarty();

        $S->assign("Me", true);
        $S->assign("Amis", $str);
        $S->assign("Tweets", $tweets);
        $S->assign("FriendsData",$friendsData);
        $S->assign("UserID", $_SESSION['id']);
        $S->assign("UserPseudo", $_SESSION['pseudo']);
        $S->assign("UserAvatar", $_SESSION['avatar']);
        $S->display(Template::getPath('Mur'));

    }



    private function show($pseudo) {
        $info = Database::select("Compte", 'id, pseudo, email, avatar', "pseudo=".  Database::q($pseudo) );
        if ( $info !=  NULL ) {


            $friends = Storage::getInstance()->fetch()->query("SELECT ProfilTwo as p FROM Friends WHERE ProfilOne=".$info[0]['id']." UNION SELECT ProfilOne as p FROM Friends WHERE ProfilTwo=".$info[0]['id'])->fetchAll(PDO::FETCH_ASSOC);
            $fs = array();
            $friendsData = array();
            foreach($friends as $f=>$v) {
                array_push($fs, $v['p']);
                $infos = Database::select("Compte", "id, pseudo, avatar", "id=".$v['p']);
                $friendsData[$infos[0]['id']] = $infos[0];
            }
            
            
            $tweets = Database::select("Tweet", "*", "Profil=".$info[0]['id']. " ", NULL, "date");
            foreach($tweets as $t=>$v) {
                $poster = ($v['Profil'] == $info[0]['id']) ? $info[0]['pseudo'] : $friendsData[$v['Profil']]['pseudo'];
                $v['content'] = preg_replace("/\@([a-zA-Z0-9.]{1,11})/", "\@<a href='/index.php/Mur/$1'>$1</a>", $v['content']);
//                echo HTML($poster. " : ".$v['content']) . " <hr> ";
                // @todo template !!!!!! + avatar
            }



            foreach ($friendsData as $key => $value) {
                $str .= $value['pseudo'] . " ";
            }

            $S = Template::getSmarty();
            $S->assign("Me", false);
            $S->assign("Amis", $str);
            $S->assign("Tweets", $tweets);
            $S->assign("FriendsData",$friendsData);
            $S->assign("UserID", $info[0]['id']);
            $S->assign("UserPseudo", $info[0]['pseudo']); //@todo a faire avatar dans template
            $S->assign("UserAvatar", $info[0]['avatar']);
            $S->display(Template::getPath('Mur'));

            
        } else {
            $this->Error("Profil Introuvable :(");
        }
    }

    public function publish() {
        if(POST('content') && Session::getInstance()->sessionCheck() && strlen($_POST['content']) <141) {
            if($id = Database::insert("Tweet", array('', $_SESSION['id'], $_POST['content'], ''), true)) {
                print json_encode(array('status'=>"OK",'id'=>$id, 'date'=>  mktime()));
            } else {
               echo json_encode(array('status'=>"NOTOK"));
            }
        } else {
            echo json_encode(array('status'=>"NOTOK"));
        }
    }

    public function delete() {
        if(Session::getInstance()->sessionCheck() && POST('id')) {
            $id = Database::select("Tweet", "id", "Profil=".$_SESSION['id']." AND id=".$_POST['id']);
            if($id) {
                if(Storage::getInstance()->fetch()->exec("DELETE FROM Tweet WHERE id=".Database::q($_POST['id'])). ' LIMIT 1') {
                    echo 'OK';
                } else {
                    echo 'NOTOK';
                }
            } else {
                echo 'NOTOK';
            }
        } else {
            echo 'NOTOK';
        }
    }

    

    private function Error($msg) {
        $S = Template::getSmarty();
        $S->assign("ErrorMsg", $msg);
        $S->display(Template::getPath("Error"));
        die();
    }
    
}
?>
